package com.jiyiren.demospring.dao;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by yiji on 2017/2/23.
 * 基础封装SQL类
 */
public abstract class BaseDao {
//  protected DriverManagerDataSource dataSource;//spring data
//  protected ComboPooledDataSource dataSource;//c3p0
    protected DataSource dataSource;//DataSource是接口，各种数据连接池都实现了该接口，因此可以通用设置
    protected Connection connection=null;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //初始化连接
    public void init(){
        try {
            connection=dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //抽象查询
    public ResultSet BaseSelect(String sql, String ... kvs) throws SQLException {
        PreparedStatement pstmt=null;
        pstmt=connection.prepareStatement(sql);
        for(int i=0;i<kvs.length;i++){
            pstmt.setString(i+1,kvs[i]);
        }
        return pstmt.executeQuery();
    }
}
